﻿using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.Data;
using System.Net;//Endpoint
using System.Net.Sockets;//包含套接字
using System.Threading;
namespace WPFExcelReport
{
    public partial class VICC_ZLAN
    {
        Socket sokWatch = null;//负责监听 客户端段 连接请求的  套接字(女生宿舍的大妈)
        Thread threadWatch = null;//负责 调用套接字， 执行 监听请求的线程
        Dictionary<string, PLCT> _Clients;
      public   Dictionary<string, PLCT> Clients
        {
            get
            {
                if(_Clients== null)
                {
                    _Clients = new Dictionary<string, PLCT>();
                }
                return _Clients;
            }
        }
       
        PLCT zLAN = null;
        bool isWatch = true;
        private DataTable _TBZL;
        public DataTable TBZL
        {
            get
            {
                if (_TBZL == null)
                {
                    dwData = TBMain.NewRow();
                    dwData["MANDANT"] = app.Mandant;
                    SResult = QBDZLAN05(dwData);
                    _TBZL = SResult.Tables[0].Copy();
                }
                return _TBZL;
            }
        }
        DataTable _TBZLAM;
        public DataTable TBZLAM
        {
            get
            {
                if (_TBZLAM == null)
                {
                    dwData = TBMain.NewRow();
                    dwData["MANDANT"] = app.Mandant;
                    SResult = QBDZLAN03(dwData);
                    _TBZLAM = SResult.Tables[0].Copy();
                }
                return _TBZLAM;
            }
        }
        /// <summary>
        /// 服务启动的时候，初始化socket服务。
        /// </summary>
        private void RequestHandle()
        {
            try
            {
                SocketHandle socketHandle = SocketHandle.getInstance();
                socketHandle.InitSocketServer();
            }
            catch (Exception ex)
            {
            }
        }
        private Thread thread;
        public void ZLStartListen()
        {
            thread = new Thread(new ThreadStart(this.RequestHandle));
            thread.Start();
            return;
            //实例化 套接字 （ip4寻址协议，流式传输，TCP协议）
            sokWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //创建 ip对象
            IPAddress address = IPAddress.Parse(app.ServiceUri);
            //创建网络节点对象 包含 ip和port
            IPEndPoint endpoint = new IPEndPoint(address, 25003);
            //将 监听套接字  绑定到 对应的IP和端口
            sokWatch.Bind(endpoint);
            //设置 监听队列 长度为10(同时能够处理 10个连接请求)
            sokWatch.Listen(10);
            threadWatch = new Thread(StartWatchClient);
            threadWatch.IsBackground = true;
            threadWatch.Start();
            Tracer.Info("ZLANServer", "StartListening");
        }
        public void ZLResetListen()
        {
            _TBZL = null;
            _TBZLAM = null;
            thread.Abort();
            if (TBZL == null)
            {
                if (TBZLAM == null)
                {
                    app.IsOnline = true;
                }
            }
            return;
            Socket oneSocket;
            Clients.Clear();
            oneSocket = sokWatch.Accept();
            oneSocket.Shutdown(SocketShutdown.Both);
            oneSocket.Close();
            sokWatch.Shutdown(SocketShutdown.Both);
            sokWatch.Disconnect(false);
            sokWatch.Close();
            threadWatch.Abort();
            threadWatch = null;
            ZLStartListen();
        }

        public void ZLANSTART()
        {
            or1 = OracleDB.CreateCommand();
            Connect2Proxy(or1, "CHKZLAPP");
            Connect2Proxy(or1, "ZLANSTART");
        }
        public void ZLANRESET()
        {
            or1 = OracleDB.CreateCommand();
            Connect2Proxy(or1, "CHKZLAPP");
            Connect2Proxy(or1, "ZLANRESET");
        }

        public void RemoveClientConnection(string key)
        {
            if (Clients.ContainsKey(key))
            {
                Clients.Remove(key);
            }
        }
        void StartWatchClient()
        {
            try
            {
                while (isWatch)
                {
                    //监听 客户端 连接请求，但是，Accept会阻断当前线程
                    Socket sokMsg = sokWatch.Accept();//监听到请求，立即创建负责与该客户端套接字通信的套接字
                    zLAN = new PLCT(sokMsg, RemoveClientConnection);
                    if (TBZL == null)
                    {
                        if (TBZLAM == null)
                        {
                            app.IsOnline = true;
                        }
                    }
                    zLAN.TBZLAM = TBZLAM;
                    string ip = zLAN.PLCIP;
                    bool IsLogged = zLAN.GetDevTyp();
                    if (!IsLogged)
                    {
                        CHKZLAN(ip);
                    }
                    //   string endp = sokMsg.RemoteEndPoint.ToString();
                    //  int idx = endp.IndexOf(':');
                    // string ip = endp.Substring(0, idx);
                    Clients[ip] = zLAN;

                    // PLCIP = ip;根据IP地址核对是否存在
                    //将负责与当前连接请求客户端 通信的套接字所在的连接通信类 对象 装入集合                     
                    Tracer.Info("ZLANServer", ip+"...Client joined......");
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        public void ZLSEND(Dictionary<string, object> pm)
        {
            try
            {
                string CHANNEL = (string)pm["CHANNEL"];
                string VALUE = (string)pm["VALUE"];
                filter = "TRIM(AMEBDEKEN) ='" + CHANNEL.Trim() + "'";
                rows = TBZL.Select(filter);
                if (rows.Length == 0)
                {
                    throw new Exception("请选择要发送的客户端～～");
                }
                string ip = rows[0]["LOCALIP"].ToString().Trim();
                if (!Clients.ContainsKey(ip))
                {
                    throw new Exception("请选择要发送的客户端～～");
                }
                zLAN = Clients[ip];
                foreach (DataRow row in rows)
                {
                    string cmd = row["AMEMESCHL"].ToString().Trim();
                    string address = row["AMEWERTVON"].ToString();
                    string count = row["AMEWERTBIS"].ToString();
                    string data = row["AMEWERTEX1"].ToString().Trim() + row["AMEWERTEX2"].ToString().Trim() + row["AMEWERTEX3"].ToString().Trim() + row["AMEWERTEX4"].ToString().Trim();
                    switch (zLAN.DEVTYP)
                    {
                        case "FXPLC":
                            cmd = "0";
                            break;
                        case "S7200":
                            if (cmd == "QW")
                                cmd = "Q_Word";
                            break;
                    }
                    CommandQ cq = new CommandQ();
                    cq.command = cmd;
                    cq.adres = address;
                    cq.count = count;
                    cq.DataSend = data;
                    zLAN.SendQ.Enqueue(cq);
                    zLAN.AutoRun();
                   // zLAN.Send(cmd, address, count, data);
                } 
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        public void ZLREAD(Dictionary<string, object> pm)
        {
            try
            {
                string CHANNEL = (string)PM["CHANNEL"];
                string VALUE = (string)PM["VALUE"];
                filter = "TRIM(AMEBDEKEN) ='" + CHANNEL.Trim() + "'";
                rows = TBZL.Select(filter);
                if (rows.Length == 0)
                {
                    throw new Exception("请选择要发送的客户端～～");
                }
                string ip = rows[0]["LOCALIP"].ToString().Trim();
                if (!Clients.ContainsKey(ip))
                {
                    throw new Exception("请选择要发送的客户端～～");
                }
                zLAN = Clients[ip];
                foreach (DataRow row in rows)
                {
                    string cmd = row["AMEMESCHL"].ToString().Trim();
                    string address = row["AMEWERTVON"].ToString();
                    string count = row["AMEWERTBIS"].ToString();
                    string data = row["AMEWERTEX1"].ToString().Trim() + row["AMEWERTEX2"].ToString().Trim() + row["AMEWERTEX3"].ToString().Trim() + row["AMEWERTEX4"].ToString().Trim();
                    switch (zLAN.DEVTYP)
                    {
                        case "FXPLC":
                            cmd = "0";
                            break;
                        case "s7200":
                            cmd = "0";
                            break;
                    }
                    zLAN.Send(cmd, address, count, data);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
    }
}
